/**
 * 语言检测中间件
 * 自动检测请求的语言并设置到请求对象中
 */

import { Request, Response, NextFunction } from 'express';
import { LanguageUtils, LanguageType, DEFAULT_LANGUAGE } from '../config/languages';

// 扩展 Request 接口，添加语言属性
declare global {
  namespace Express {
    interface Request {
      language: LanguageType;
    }
  }
}

/**
 * 语言检测中间件
 * 优先级：查询参数 > 请求头 > 默认语言
 */
export const languageDetector = (req: Request, res: Response, next: NextFunction): void => {
  try {
    let language: LanguageType = DEFAULT_LANGUAGE;

    // 1. 优先从查询参数获取语言
    const queryLang = req.query.lang as string;
    if (queryLang) {
      language = LanguageUtils.getLanguageFromQuery(queryLang);
    } else {
      // 2. 从请求头获取语言
      const acceptLanguage = req.headers['accept-language'];
      language = LanguageUtils.getLanguageFromHeader(acceptLanguage);
    }

    // 设置语言到请求对象
    req.language = language;

    // 添加语言信息到响应头
    res.setHeader('Content-Language', language);
    res.setHeader('X-Request-Language', language);

    next();
  } catch (error) {
    // 如果语言检测失败，使用默认语言
    req.language = DEFAULT_LANGUAGE;
    res.setHeader('Content-Language', DEFAULT_LANGUAGE);
    res.setHeader('X-Request-Language', DEFAULT_LANGUAGE);
    next();
  }
};

/**
 * 强制语言中间件
 * 强制使用指定的语言，忽略请求中的语言设置
 * @param forcedLanguage 强制使用的语言
 */
export const forceLanguage = (forcedLanguage: LanguageType) => {
  return (req: Request, res: Response, next: NextFunction): void => {
    req.language = forcedLanguage;
    res.setHeader('Content-Language', forcedLanguage);
    res.setHeader('X-Request-Language', forcedLanguage);
    next();
  };
};

/**
 * 语言验证中间件
 * 验证请求中的语言是否支持，如果不支持则返回错误
 */
export const validateLanguage = (req: Request, res: Response, next: NextFunction): void => {
  const language = req.language;
  
  if (!LanguageUtils.isSupportedLanguage(language)) {
    res.status(400).json({
      success: false,
      code: 400,
      message: `不支持的语言: ${language}`,
      timestamp: new Date().toISOString(),
      path: req.originalUrl
    });
    return;
  }

  next();
};

/**
 * 获取当前请求语言的工具函数
 * @param req 请求对象
 * @returns 语言代码
 */
export const getCurrentLanguage = (req: Request): LanguageType => {
  return req.language || DEFAULT_LANGUAGE;
};

/**
 * 语言信息中间件
 * 在响应中添加支持的语言信息
 */
export const languageInfo = (req: Request, res: Response, next: NextFunction): void => {
  // 添加支持的语言列表到响应头
  const supportedLanguages = LanguageUtils.getSupportedLanguages();
  res.setHeader('X-Supported-Languages', supportedLanguages.join(', '));
  
  // 添加当前语言信息到响应头
  res.setHeader('X-Current-Language', req.language);
  // 移除包含非ASCII字符的显示名称头，因为HTTP头不支持非ASCII字符
  // res.setHeader('X-Current-Language-Name', LanguageUtils.getLanguageDisplayName(req.language));
  
  next();
};

export default languageDetector; 